package cn.edu.nuc.bre.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.activiti.engine.identity.Group;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import cn.edu.nuc.bre.dto.UserInfo;
import cn.edu.nuc.bre.entity.Task;
import cn.edu.nuc.bre.entity.TransDetail;
import cn.edu.nuc.bre.entity.TransType;
import cn.edu.nuc.bre.entity.Transaction;
import cn.edu.nuc.bre.service.interfaces.GroupService;
import cn.edu.nuc.bre.service.interfaces.TransDetailService;
import cn.edu.nuc.bre.service.interfaces.TransTypeService;
import cn.edu.nuc.bre.service.interfaces.TransactionService;

/**
 * 事务Action
 * 
 * @author 王凯
 *
 */
@Controller
@Scope("prototype")
public class TransactionAction extends ActionSupport {

	/**
	 * 序列化id
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 事务业务对象
	 */
	@Autowired
	private TransactionService transactionService;

	/**
	 * 事务明细业务对象
	 */
	@Autowired
	private TransDetailService transDetailService;
	
	/**
	 * 事务类型业务对象
	 */
	@Autowired
	private TransTypeService transTypeService;
	
	/**
	 * 部门业务对象
	 */
	@Autowired
	private GroupService groupService;

	/**
	 * Struts 2的上下文环境
	 */
	private ActionContext ctx = ActionContext.getContext();

	/**
	 * 事务实体类对象（接收参数用）
	 */
	private Transaction transaction = new Transaction();

	/**
	 * 用户的操作种类 delay:延期
	 */
	private String option;

	/**
	 * 接受返回事务明细
	 */
	private Integer serviceType;
	
	/**
	 * 接受事务类型
	 */
	private String typeDetailstring;
	
	/**
	 * 接收要查询的事务明细的id
	 */
	private Integer typeDetail;

	/**
	 * 接受返回事务其他信息
	 */
	private String details;

	/**
	 * 查询我的任务列表（用于显示待处理、关注中、已处理的任务）
	 * 
	 * @return
	 */
	public String findMyTaskList() {

		// 1.从Session中取出登录信息，得到登录的用户名（默认只存Firstname，lastname废弃不用）
		UserInfo userInfo = (UserInfo) ctx.getSession().get("userInfo");
		String username = userInfo.getUser().getFirstName();

		// 2.查询出待拾取任务
		List<Transaction> needClaimList = transactionService.findNeedClaimByAssignee(username);

		// 3.查询出待办理任务
		List<Transaction> needDealList = transactionService.findNeedDealByAssignee(username);

		// 4.查询出关注中任务
		List<Transaction> followingList = transactionService.findFollowingByAssignee(username);

		// 5.查询出已办完任务
		List<Transaction> finishedList = transactionService.findFinishedByAssignee(username);

		// 6.保存所有的结果集并带到页面上
		ctx.put("needClaimList", needClaimList);
		ctx.put("needDealList", needDealList);
		ctx.put("followingList", followingList);
		ctx.put("finishedList", finishedList);
		ctx.put("nowtime", new Date()); // 放置当前系统时间，用于判断是否超时

		return SUCCESS;
	}

	/**
	 * 查看事务详情
	 * 
	 * @return
	 */
	public String findTransactionDetail() {

		// 1.从参数中得到事务id
		Integer tid = transaction.getTid();

		// 2.根据事务id查询事务的详细信息
		Transaction transaction = transactionService.findById(tid);

		// 3.根据事务id查询和事务相关的批注
		List<Comment> relatedCommentList = transactionService.findCommentsById(tid);

		// 4.查询事务相关的子任务列表
		List<Task> relatedTaskList = transactionService.findChildTasksById(tid);

		// 5.查询事务对应的事务明细
		TransDetail transDetail = transDetailService.findById(transaction.getTdid());

		// 6.保存查询结果
		ctx.put("transaction", transaction);
		ctx.put("relatedCommentList", relatedCommentList);
		ctx.put("relatedTaskList", relatedTaskList);
		ctx.put("transDetail", transDetail);
		ctx.put("nowtime", new Date()); // 放置当前系统时间，用于判断是否超时
		ctx.put("option", option); // 操作种类：是不是延期？是不是处理等等

		return SUCCESS;
	}
	
	/**
	 * 事务类型改变事件(新事务申报ajax)
	 * @return
	 */
	public String typeChange() {
		
		typeDetailstring = "";
		
		//得到事务类型
		TransType transType = transTypeService.findById(serviceType);
		
		//得到事务类型对应的事务详情
		List<TransDetail> transDetails = transDetailService.findDetailsByType(transType.getTtypeid());
		
		//拼接目标字符串
		for (int i = 0; i < transDetails.size(); i++) {
			typeDetailstring = typeDetailstring + transDetails.get(i).getTdid();
			typeDetailstring = typeDetailstring + "@@";
			typeDetailstring = typeDetailstring + transDetails.get(i).getTdname();
			if (i + 1 != transDetails.size()) { //不是最后一个
				typeDetailstring = typeDetailstring + "@@";
			}
		}
		
        return "success";  
    }	

	/**
	 * 事务明细改变事件(新事务申报ajax)
	 * @return
	 */
	public String detailsChange() { 
		
		//得到事务明细的详细信息
		TransDetail detail = transDetailService.findById(typeDetail);
		
		//查询出保障部门的名称
		Group group = groupService.findById(detail.getEnsuredeptid());
		
		//拼接字符串
		details = detail.getDlevel() + "@@" 
				+ group.getName() + "@@"
				+ detail.getServicetime() + "@@"
				+ detail.getEndtime() + "@@"
				+ detail.getNote();
		
        return "success";  
    }
	
	/**
	 * 初始化新事务申报
	 * @return
	 */
	public String initAdd() {
		
		//加载出所有的事务类型（未禁用）
		List<TransType> transTypeList = transTypeService.findAll();
		
		//保存结果集
		ActionContext.getContext().put("transTypeList", transTypeList);
		
		return "success";
	}

	/**
	 * 新事务申报
	 * 
	 * @return
	 * @throws Exception
	 */
	public String demandReport() throws Exception {
		
		//1.接收各个参数
		
		//1.1 设置事务类型的参数(只有名称)
		TransType findtransType = transTypeService.findById(serviceType);
		String ttname = findtransType.getTtname();
		transaction.setTtname(ttname);
		
		//1.2 设置事务明细的参数（类型和名称）
		TransDetail findTransDetail = transDetailService.findById(typeDetail);
		String tdname = findTransDetail.getTdname();
		transaction.setTdid(typeDetail);
		
		//1.3 计算并设置超时时间
		
		//首先获取超时时间,对于新申报事务来说，超时时间就是初审时限
		Integer outhour = findTransDetail.getExamtime();
		
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR_OF_DAY, outhour);
		
		transaction.setTtimeout(calendar.getTime());
		
		//2.执行启动流程实例的方法并继续设置剩余参数
		transactionService.addAndStart(transaction);

		return "success";
	}

	/////////////////////////////////////////////////////////////////
	public TransactionService getTransactionService() {
		return transactionService;
	}

	public void setTransactionService(TransactionService transactionService) {
		this.transactionService = transactionService;
	}

	public Transaction getTransaction() {
		return transaction;
	}

	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
	}

	public TransDetailService getTransDetailService() {
		return transDetailService;
	}

	public void setTransDetailService(TransDetailService transDetailService) {
		this.transDetailService = transDetailService;
	}

	public String getOption() {
		return option;
	}

	public void setOption(String option) {
		this.option = option;
	}

	public String getTypeDetailstring() {
		return typeDetailstring;
	}

	public void setTypeDetailstring(String typeDetailstring) {
		this.typeDetailstring = typeDetailstring;
	}

	public Integer getTypeDetail() {
		return typeDetail;
	}

	public void setTypeDetail(Integer typeDetail) {
		this.typeDetail = typeDetail;
	}

	public Integer getServiceType() {
		return serviceType;
	}

	public void setServiceType(Integer serviceType) {
		this.serviceType = serviceType;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	public TransTypeService getTransTypeService() {
		return transTypeService;
	}

	public void setTransTypeService(TransTypeService transTypeService) {
		this.transTypeService = transTypeService;
	}

}
